/*
Designer   : Renyangang

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

	http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package device

import (
	"context"
	"fpga-vboard/fpga"
	"fpga-vboard/logger"
	"fpga-vboard/pins"
)

func init() {
	config := &CPUConfig{
		DeviceInfo: DeviceInfo{
			Id:         CPU_DEFAULT,
			Type:       CPU,
			Name:       "cpu_verilator",
			InputPins:  make([]*pins.PinDef, 0),
			OutputPins: make([]*pins.PinDef, 0),
			Enable:     true,
			IsOptional: false,
		},
		VerilatorConfig: &fpga.VerilatorConfig{
			VerilatorModuleFilePath: "",
			VerilogModulePaths:      []string{},
		},
		LibPath: "",
	}
	RegisterDev(config)
}

type Cpu struct {
	*DeviceBase
	InputPins      []*pins.SignalPin
	OutputPins     []*pins.SignalPin
	isInit         bool
	ClockFrequency int
	fgpaPlugin     *fpga.FpgaPlugin
	libPath        string
}

func NewCpu(config *CPUConfig) *Cpu {
	return &Cpu{
		DeviceBase: &DeviceBase{
			Config: config,
		},
		isInit:  false,
		libPath: config.LibPath,
	}
}

func (cpu *Cpu) Start(ctx context.Context) error {
	if !cpu.isInit {
		cpu.fgpaPlugin = fpga.NewFpgaPlugin("default_cpu", cpu.libPath, cpu.InputPins, cpu.OutputPins)
		err := cpu.fgpaPlugin.Init()
		if err != nil {
			logger.FatalEvent("Failed to init FPGA plugin: %v", err)
			return err
		}
		cpu.isInit = true
	}
	return nil
}

func (cpu *Cpu) Run(ctx context.Context) {
	cpu.fgpaPlugin.Eval()
}

func (cpu *Cpu) Stop(ctx context.Context) {
	cpu.fgpaPlugin.Stop()
	cpu.fgpaPlugin.Uninit()
}
